//
//  HSTopicDetailVC.m
//  HolyShit
//
//  Created by Robin on 2017/4/5.
//  Copyright © 2017年 HolyShit. All rights reserved.
//

#import "HSTopicDetailVC.h"
#import "HSTopicDetailCell.h"
#import "HSTopicDetailVM.h"
#import "HSCommentKeyboardView.h"
#import "HSLoginVC.h"

@interface HSTopicDetailVC ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) HSTopicDetailVM *listVM;
@property (nonatomic, strong) HSTopicDetailCell *tmpCell;
@property (nonatomic, copy) NSString *topicTitle;
@property (nonatomic, strong) HSCommentKeyboardView *textArea;

@end

@implementation HSTopicDetailVC

- (instancetype)initWithTitle:(NSString *)title id:(NSString *)id
{
    if (self = [super init]) {
        _listVM = [[HSTopicDetailVM alloc] initWithId:id];
        _topicTitle = title;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self rightTitleWithTitle:@"回复"];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.textArea];
    @weakify(self);
    [self.hintView setReloadBlock:^{
        @strongify(self);
        self.hintView.hintState = MYHintStateLoading;
        [self refresh];
    }];
    self.hintView.reloadBlock();

    [self.view bk_whenTapped:^{
        @strongify(self);
        [self.view endEditing:YES];
    }];
}

- (void)rightButtonTouch
{
    [self replyWithName:self.listVM.forums[0].attributes.username];
}

- (void)replyWithName:(NSString *)name
{
    if (![[NSUserDefaults standardUserDefaults] objectForKey:userNameKey]) {
        return [self my_push:[HSLoginVC new]];
    }
    self.textArea.placeholderLb.text = [NSString stringWithFormat:@"@%@：",name];
    [self.textArea.textView becomeFirstResponder];
}

- (void)refresh
{
    @weakify(self);
    [[self.listVM.dataCommand execute:nil] subscribeNext:^(id x) {
        @strongify(self);
        self.hintView.hintState = MYHintStateHidden;
        [self.tableView endRefreshAndLoadMore];
        [self.tableView reloadData];
    } error:^(NSError *error) {
        @strongify(self);
        self.hintView.hintState = MYHintStateNoData;
        [self.tableView endRefreshAndLoadMore];
        [UIWindow showError:error];
    }];
}

- (void)loadmore
{
    @weakify(self);
    [[self.listVM.loadmoreCommand execute:nil] subscribeNext:^(id x) {
        @strongify(self);
        [self.tableView endRefreshAndLoadMore];
        [self.tableView reloadData];
    } error:^(NSError *error) {
        @strongify(self);
        [self.tableView endRefreshAndLoadMore];
        [UIWindow showError:error];
    }];
}

- (void)hideTextArea
{
    [self.view endEditing:YES];
    @weakify(self);
    [[GCDQueue mainQueue]queueBlock:^{
        @strongify(self);
        if(self.textArea.keyboardDidHide){
            self.textArea.keyboardDidHide();
        }
    } afterDelay:0.2];
}

#pragma mark - uitableview

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.listVM.forums.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HSForumListModel *model = self.listVM.forums[indexPath.row];
    if (model.attributes.cellHeight < 1) {
        if (!self.tmpCell) {
            self.tmpCell = [HSTopicDetailCell new];
        }
        self.tmpCell.model = model;
    }
    return model.attributes.cellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HSTopicDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([HSTopicDetailCell class])];
    if (!cell.replyBlock) {
        @weakify(self);
        [cell setReplyBlock:^(NSString *name) {
            @strongify(self);
            [self replyWithName:name];
        }];
    }
    cell.model = self.listVM.forums[indexPath.row];
    return cell;
}

#pragma mark - getter


- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - NavBarHeight) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = CLEAR_COLOR;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        [_tableView addRefreshTarget:self action:@selector(refresh)];
        [_tableView addLoadMoreTarget:self action:@selector(loadmore)];
        [_tableView registerClass:[HSTopicDetailCell class] forCellReuseIdentifier:NSStringFromClass([HSTopicDetailCell class])];
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0)];
        UILabel *label = [UILabel labelWithFont:MYFont(Font34) color:HEXCOLOR(HSColorBlack)];
        label.numberOfLines = 0;
        [view addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(10);
            make.top.mas_equalTo(15);
            make.right.mas_equalTo(-10);
        }];
        label.text = self.topicTitle;
        [view layoutIfNeeded];
        [view layoutSubviews];
        view.height = label.bottom + 15;
        _tableView.tableHeaderView = view;
    }
    return _tableView;
}

- (HSCommentKeyboardView *)textArea
{
    if (!_textArea) {
        _textArea = [HSCommentKeyboardView new];
        _textArea.left = 0;
        _textArea.top = self.tableView.bottom;
        @weakify(self);
        [_textArea setKeyboardDidHide:^{
            @strongify(self);
            self.textArea.top = self.tableView.bottom;
//            if(self.bEndEditShowInfo){
//                self.bEndEditShowInfo = NO;
//                self.contentView.userInteractionEnabled = NO;
//                [self.infoView show];
//            }
        }];
        [_textArea.sendBtn bk_addEventHandler:^(id sender) {
            @strongify(self);
            if (![self.textArea.textView.text isNotBlank]) {
                [UIWindow showFailedMsg:@"评论不能为空"];
                self.textArea.textView.text = @"";
                [self.textArea calculateTextViewHeight];
                return;
            }
//            NSString *msg = self.textArea.textView.text;
            [self.textArea setHideHandle:^{
                [UIWindow showProgressWithMessage:@"评论中..."];
                [[GCDQueue mainQueue] queueBlock:^{
                    [UIWindow showSuccessMsg:@"评论成功，等待审核"];
                } afterDelay:1.2];
            }];
            self.textArea.textView.text = @"";
            [self.textArea calculateTextViewHeight];
            [self hideTextArea];
        } forControlEvents:UIControlEventTouchUpInside];
    }
    return _textArea;
}

@end
